﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Text;
using Repository.Abstract;
using DomainModel.Entities;

namespace Repository.Concrete
{
    public class SqlBaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : class, IEntityObject, IAuditableEntity, IEntityWithUser
    {
        private readonly Table<TEntity> _entityTable;

        public SqlBaseRepository(string connectionString)
        {
            _entityTable = (new DataContext(connectionString)).GetTable<TEntity>();
        }
        
        public virtual IQueryable<TEntity> GetAll
        {
            get { return _entityTable; }
        }

        public virtual void Delete(TEntity entity)
        {
            _entityTable.DeleteOnSubmit(entity);
            _entityTable.Context.SubmitChanges();
        }

        public void Add(TEntity enity, Guid userId)
        {
            enity.UserId = userId;
            enity.DateCreate = DateTime.Now;
            _entityTable.InsertOnSubmit(enity);
            _entityTable.Context.SubmitChanges();
        }

        public virtual void Save(TEntity enity, Guid userId)
        {
            _entityTable.Context.Refresh(RefreshMode.KeepCurrentValues, enity);
            _entityTable.Context.SubmitChanges();            
        }
    }
}
